import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:joyagoo/pages/widget/JoyEmptyWidget.dart';
import 'package:joyagoo/pages/widget/Joy_NoNetworkTip_Widget.dart';
import '../config/app_colors.dart';
import '../config/app_url_address.dart';
import '../model/categoryModel.dart';
import '../model/productListModel.dart';
import '../utils/JoyBlocUtil.dart';
import '../utils/currency_manager.dart';
import 'joy_home_bloc.dart';
import 'widget/joy_product_card_widget.dart';


//JoyCategoryContentPage

class JoyCategoryContentPage extends StatefulWidget {
  final String categoryName;
  final String categoryId;
  final bool? fromHome;

  const JoyCategoryContentPage({Key? key, required this.categoryName,required this.categoryId,this.fromHome}) : super(key: key);

  @override
  _JoyCategoryContentPageState createState() => _JoyCategoryContentPageState();
}

class _JoyCategoryContentPageState extends State<JoyCategoryContentPage>
    with AutomaticKeepAliveClientMixin {

  // 保持页面状态
  @override
  bool get wantKeepAlive => true;
  
  // 货币变化监听器
  late CurrencyChangeListener _currencyChangeListener;

  // 排序选项
  String _selectedPriceSort = 'Price';
  String _selectedTimeSort = 'Time';
  String _selectedSortOption = 'Most Popular';

  // 选中的分类ID
  String _selectedCategoryId = '0';

  // 模拟商品数据
  List<Map<String, dynamic>> products = [];

  late JoyHomeBloc mainHomeBloc;
  late EasyRefreshController _refreshController;
  List JOYProductList = [];

  bool isError = false;

  String error_joy = "No Data";
  bool isNetError_joy = false;
  String errorImage_joy = "";
  int pageNo = 1;
  int pageSize = 20;

  List<CategoryModel> catagateList = [];

  String chooseCategoryName = "";
  String chooseCategoryNameTemp = "All";


//createAt
// price
// sort
  String sortColumn = ""; // 🔥 Most Popular 默认为空字符串

  ///0-正序
  /// 1-倒叙
  String orderBy = ""; // 🔥 Most Popular 默认为空字符串


  @override
  void initState() {
    super.initState();

    _selectedCategoryId = widget.categoryId;

    _refreshController = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
    chooseCategoryName = widget.categoryName;
    
    // 初始化货币变化监听器
    _currencyChangeListener = (newCurrency, oldCurrency) {
      print('Category page: Currency changed from ${oldCurrency.code} to ${newCurrency.code}');
      // 货币改变时刷新分类页面数据
      _refreshCategoryData();
    };
    
    // 添加货币变化监听器
    CurrencyManager.instance.addListener(_currencyChangeListener);
  }

  @override
  void dispose() {
    // 移除货币变化监听器
    CurrencyManager.instance.removeListener(_currencyChangeListener);
    super.dispose();
  }

  // 刷新分类页面数据
  void _refreshCategoryData() {
    if (mounted) {
      // 重置页码
      pageNo = 1;
      // 清空当前列表
      JOYProductList.clear();
      // 重新加载数据
      loadData();
      
      // 不显示重复提示，只刷新数据
    }
  }

  Widget _buildMain(){
    bool isHome = widget.fromHome??false;
    if(isHome == true){

      return Scaffold(
        appBar: AppBar(
          backgroundColor: AppColors.backHomeYellowGround,
          title: Text(widget.categoryName,      style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),),
          leading: GestureDetector(
            onTap: () => Get.back(),
            child: Container(
              margin: EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 10),
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12.r),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 8,
                    offset: Offset(0, 2),
                  ),
                ],
              ),
              child: Icon(
                Icons.arrow_back_ios_new,
                color: AppColors.primaryVariant,
                size: 18.sp,
              ),
            ),
          ),
        ),
        body: BlocMain(),
      );
    }
    return BlocMain();
  }

  Widget refresh(){
    return EasyRefresh(
        controller: _refreshController,
        // 🔥 设置下拉刷新样式 - 文字颜色为黑色
        header: const ClassicHeader(
          dragText: 'Pull to refresh',
          armedText: 'Release to refresh', 
          readyText: 'Refreshing...',
          processingText: 'Refreshing...',
          processedText: 'Refresh completed',
          noMoreText: 'No more data',
          failedText: 'Refresh failed',
          messageText: 'Last updated at %T',
          textStyle: TextStyle(color: Colors.black), // 🔥 设置文字颜色为黑色
          messageStyle: TextStyle(color: Colors.black54), // 🔥 设置消息文字颜色为黑色透明
        ),
        // 🔥 设置上拉加载样式 - 文字颜色为黑色  
        footer: const ClassicFooter(
          dragText: 'Pull to load',
          armedText: 'Release to load',
          readyText: 'Loading...',
          processingText: 'Loading...',
          processedText: 'Loading completed',
          noMoreText: 'No more data',
          failedText: 'Loading failed',
          messageText: 'Last updated at %T',
          textStyle: TextStyle(color: Colors.black), // 🔥 设置文字颜色为黑色
          messageStyle: TextStyle(color: Colors.black54), // 🔥 设置消息文字颜色为黑色透明
        ),
        onRefresh: () async {
          loadData();
        },
        onLoad:  ()async {
          loadMoreData();
        } ,
        child: showContent()
    );
  }

  void loadData(){
    pageNo = 1;
    mainHomeBloc.add(GetJOYSearchCategoryProductEvent(context,chooseCategoryName,pageNo,pageSize,sortColumn: sortColumn,orderBy: orderBy));

  }

  void loadMoreData(){
    pageNo = pageNo + 1;
    mainHomeBloc.add(GetJOYSearchCategoryProductEvent(context,chooseCategoryName,pageNo,pageSize,sortColumn: sortColumn,orderBy: orderBy));

  }


  // 生成模拟数据
  void _generateMockData() {
    products = List.generate(20, (index) => {
      'name': '${widget.categoryName} Product ${index + 1}',
      'price': (50 + index * 10).toDouble(),
      'image': 'https://img2.baidu.com/it/u=2101541482,3418856015&fm=253&fmt=auto&app=138&f=JPEG?w=1269&h=800',
      'time': DateTime.now().subtract(Duration(days: index)),
    });
  }

  // 价格排序
  void _sortByPrice(String sortType) {
    setState(() {
      _selectedPriceSort = sortType;
      if (sortType == 'Price Low to High') {
        products.sort((a, b) => a['price'].compareTo(b['price']));
      } else if (sortType == 'Price High to Low') {
        products.sort((a, b) => b['price'].compareTo(a['price']));
      }
    });
  }

  // 时间排序
  void _sortByTime(String sortType) {
    setState(() {
      _selectedTimeSort = sortType;
      if (sortType == 'Latest') {
        products.sort((a, b) => b['time'].compareTo(a['time']));
      } else if (sortType == 'Oldest') {
        products.sort((a, b) => a['time'].compareTo(b['time']));
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    return _buildMain();
  }
  Widget errornetwork(){
    return Padding(padding: EdgeInsets.only(left: 0.w,right: 0.w),
      child: JoyNoNetworkTipWidget(haveNetWorkCallBack: (){
        if(this.isError == true){
          mainHomeBloc.add(GetJOYHomeCategoryEvent(context,appHomeType,widget.categoryId));
        }
      },noNetWorkCallBack: (){
        this.isError = true;
      },),
    );
  }
  Widget BlocMain(){
    return JoyBlocUtil.getAppNoBarBloc(builder: (context, state) {
      return Stack(
        children: [
        Container(
          // 🔥 修改背景颜色为 AppColors.secondary
          color: AppColors.secondary,
          height: ScreenUtil().screenHeight,
        ),
          Column(
            children: [
              // errornetwork(),
              Expanded(
                child: categotyMain(),
              )
            ],
          ),


        ],
      );
    }, create: (_) {
      mainHomeBloc = JoyHomeBloc();
      mainHomeBloc.add(GetJOYHomeCategoryEvent(context,appHomeType,widget.categoryId));

      return mainHomeBloc;
    }, buildWhen: (previousState, state) {

      if(state is GetJOYHomeCategoryEventSuccess){
        debugPrint("=====Category${state.data}");
        List cataList = state.data;
        catagateList.clear();
        if(cataList.isNotEmpty){
          CategoryModel allModel = CategoryModel(categoryName: "All", categoryId: 0, categoryDesc: "");
          catagateList = List<CategoryModel>.from(state.data.map((x) => CategoryModel.fromJson(x is Map<String, dynamic> ? x : x.toJson())));
          catagateList.insert(0, allModel);
          chooseCategoryName = widget.categoryName;
          _selectedCategoryId = "0";
        }
        loadData();
        return true;
      }
      if(state is GetJOYHomeCategoryEventFailure){
        loadData();
        return true;
      }
      if(state is GetJOYSearchCategoryProductEventSuccess){
        isNetError_joy = false;

        debugPrint("=====product${state.data}");
        ProductListModel modellist = state.data;
        if(pageNo == 1){
          JOYProductList.clear();
          JOYProductList.addAll(modellist.productModels);
        }else{
          JOYProductList.addAll(modellist.productModels);
        }
        _refreshController.resetHeader();
        _refreshController.finishLoad();
        _refreshController.finishRefresh();
        _refreshController.resetFooter();
        if(modellist.productModels.length < pageSize){
          _refreshController.finishLoad(IndicatorResult.noMore);
        }else{
          _refreshController.finishLoad();
        }

        if(JOYProductList.isEmpty){
          error_joy = "No products available";
        }

        return true;

      }
      if(state is GetJOYSearchCategoryProductEventFailure){
        isNetError_joy = true;
        error_joy = state.errMsg??"request Failed";
        pageNo = pageNo - 1;
        if(pageNo <= 0){
          pageNo = 1;
        }
        _refreshController.finishLoad();
        _refreshController.finishRefresh();
        _refreshController.resetHeader();
        _refreshController.resetFooter();

      }
      return true;

    });
  }


  Widget showEmpty(){
    return JoyEmptyWidget(messageError: error_joy, isNetError: isNetError_joy, errorImagePath: errorImage_joy,isShowBtn: isNetError_joy, tapOnCallBack: (){
      loadData();
    });
  }

  Widget categotyMain(){

    return Column(
      children: [
        errornetwork(),
        // 分类标签
        _buildCategoryTags(),
        
        // 筛选按钮
        _buildFilterButton(),
        
        // 排序选项栏
        // _buildSortBar(),
        // 商品列表
        Expanded(
          child: refresh(),
        )
      ],
    );
  }


  Widget showContent1(){
    if(JOYProductList.isEmpty){
      return Expanded(
        child:  Container(
          height: ScreenUtil().screenHeight - 200,
          child: showEmpty(),
        ),
      );
    }

    return Expanded(
      child: _buildProductList(),
    );
  }
  Widget showContent(){
    if(JOYProductList.isEmpty){
      return Container(
        height: ScreenUtil().screenHeight - 200,
        width: ScreenUtil().screenWidth,
        child: showEmpty(),
      );
    }

    return _buildProductList();
  }

  // 构建商品列表
  Widget _buildProductList() {
    return GridView.builder(
      padding: EdgeInsets.all(12),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        childAspectRatio: 0.72,
        crossAxisSpacing: 16,
        mainAxisSpacing: 16,
      ),
      itemCount: JOYProductList.length,
      itemBuilder: (context, index) {
        ProductModel? productmodel = JOYProductList[index];
        return JoyProductCardWidget(
          productModel: productmodel,
          onTap: () {
            // TODO: 跳转到商品详情页
          },
          onFavorite: () {
            // TODO: 实现收藏功能
          },
        );;
      },
    );
  }
  // 构建排序栏
  Widget _buildSortBar() {
    return Container(
      height: 40,
      padding: EdgeInsets.symmetric(horizontal: 8,vertical: 5),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(color: Colors.grey[300]!, width: 0.5),
        ),
      ),
      child: Row(
        children: [
          // 价格排序
          Expanded(
            child: PopupMenuButton<String>(
              child: Container(
                height: 25,
                alignment: Alignment.center,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      _selectedPriceSort,
                      style: TextStyle(
                        color: _selectedPriceSort != 'Price' ? AppColors.buttonTextPrimary : Colors.black87,
                        fontWeight: _selectedPriceSort != 'Price' ? FontWeight.bold : FontWeight.normal,
                      ),
                    ),
                    Icon(
                      Icons.arrow_drop_down,
                      color: _selectedPriceSort != 'Price' ? AppColors.buttonTextPrimary : Colors.black87,
                    ),
                  ],
                ),
              ),
              itemBuilder: (context) => [
                PopupMenuItem(value: 'Price Low to High', child: Text('Price Low to High')),
                PopupMenuItem(value: 'Price High to Low', child: Text('Price High to Low')),
              ],
              onSelected: _sortByPrice,
            ),
          ),
          Container(
            width: 1,
            height: 30,
            color: Colors.grey[300],
          ),
          // 时间排序
          Expanded(
            child: PopupMenuButton<String>(
              child: Container(
                height: 40,
                alignment: Alignment.center,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      _selectedTimeSort,
                      style: TextStyle(
                        color: _selectedTimeSort != 'Time' ? AppColors.primary : Colors.black87,
                        fontWeight: _selectedTimeSort != 'Time' ? FontWeight.bold : FontWeight.normal,
                      ),
                    ),
                    Icon(
                      Icons.arrow_drop_down,
                      color: _selectedTimeSort != 'Time' ? AppColors.primary : Colors.black87,
                    ),
                  ],
                ),
              ),
              itemBuilder: (context) => [
                PopupMenuItem(value: 'Latest', child: Text('Latest')),
                PopupMenuItem(value: 'Earliest', child: Text('Earliest')),
              ],
              onSelected: _sortByTime,
            ),
          ),
        ],
      ),
    );
  }

  // 构建分类标签
  Widget _buildCategoryTags() {
    if (catagateList.isEmpty) {
      return SizedBox.shrink();
    }

    return Container(
      width: ScreenUtil().screenWidth,
      margin: EdgeInsets.symmetric(horizontal: 4.w, vertical: 4.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Wrap(
            spacing: 6.w,
            runSpacing: 6.h,
            children: catagateList.map<Widget>((category) {
              final isSelected = _selectedCategoryId == category.categoryId.toString();
              return GestureDetector(
                onTap: () {
                  _onCategorySelected(category.categoryId.toString(), category.categoryName);
                },
                child: AnimatedContainer(
                  duration: Duration(milliseconds: 200),
                  padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 4.h),
                  decoration: BoxDecoration(
                    color: isSelected ? AppColors.primaryVariant : Colors.white,
                    borderRadius: BorderRadius.circular(10.r),
                    border: Border.all(
                      color: isSelected ? AppColors.primaryVariant : Colors.grey[300]!,
                      width: 1.5,
                    ),
                    // boxShadow: [
                    //   BoxShadow(
                    //     color: isSelected
                    //         ? ALBAppStyle.mainColor.withOpacity(0.3)
                    //         : Colors.grey.withOpacity(0.1),
                    //     blurRadius: isSelected ? 8 : 4,
                    //     offset: Offset(0, 2),
                    //   ),
                    // ],
                  ),
                  child: Text(
                    category.categoryName,
                    style: TextStyle(
                      color: isSelected ? Colors.white : Colors.black87,
                      fontSize: 10.sp,
                      fontWeight: isSelected ? FontWeight.w400 : FontWeight.w400,
                    ),
                  ),
                ),
              );
            }).toList(),
          ),
        ],

        
      ),
    );
  }

  // 分类选择回调
  void _onCategorySelected(String categoryId, String categoryName) {
    if (_selectedCategoryId != categoryId) {
      setState(() {
        _selectedCategoryId = categoryId;
      });

      if (categoryName == "All") {
        categoryName = widget.categoryName;
      }
      chooseCategoryName = categoryName;
      // 更新数据
      pageNo = 1;
      JOYProductList.clear();
      mainHomeBloc.add(GetJOYSearchCategoryProductEvent(
          context, chooseCategoryName, pageNo, pageSize,sortColumn: sortColumn,orderBy: orderBy));
    }
  }

  // 构建筛选按钮
  Widget _buildFilterButton() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: _showSortBottomSheet,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(16.r),

              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(
                    Icons.filter_alt_sharp,
                    color: AppColors.primaryVariant,
                    size: 16.sp,
                  ),
                  SizedBox(width: 4.w),
                  Text(
                    _selectedSortOption,
                    style: TextStyle(
                      color: AppColors.primaryVariant,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 显示排序底部弹出框
  void _showSortBottomSheet() {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (BuildContext context) {
        return Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20.r),
              topRight: Radius.circular(20.r),
            ),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 拖拽指示器
              Container(
                margin: EdgeInsets.only(top: 12.h, bottom: 8.h),
                width: 40.w,
                height: 4.h,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(2.r),
                ),
              ),
              
              // 标题
              Padding(
                padding: EdgeInsets.symmetric(vertical: 16.h),
                child: Text(
                  'Sort by',
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
              ),
              
              // 排序选项
              ..._buildSortOptions(),
              
              SizedBox(height: 20.h),
            ],
          ),
        );
      },
    );
  }

  // 构建排序选项
  List<Widget> _buildSortOptions() {
    final options = [
      'Most Popular',
      'Newest',
      'Price High to Low',
      'Price Low to High',
    ];

    return options.map((option) {
      final isSelected = _selectedSortOption == option;
      return Container(
        margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 4.h),
        child: GestureDetector(
          onTap: () {
            setState(() {
              _selectedSortOption = option;
            });
            Navigator.pop(context);
            _applySorting(option);
          },
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
            decoration: BoxDecoration(
              color: isSelected ? AppColors.primaryVariant : Color(0xFFF0F2F4),
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: Center(
              child: Text(
                option,
                style: TextStyle(
                  color: isSelected ? Colors.white : AppColors.textSecondary,
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ),
        ),
      );
    }).toList();
  }

  // 应用排序
  void _applySorting(String sortOption) {
    setState(() {
      _selectedSortOption = sortOption;
    });
    
    // 这里可以根据排序选项重新加载数据或对现有数据进行排序
    // 例如：
    switch (sortOption) {
      case 'Most Popular':
        sortColumn  = "";
        orderBy = "";
        // 按最受欢迎排序
        break;
      case 'Price Low to High':
        sortColumn  = "price";
        orderBy = "0";
        // 按价格从低到高排序
        break;
      case 'Price High to Low':
        sortColumn  = "price";
        orderBy = "1";
        // 按价格从高到低排序
        break;
      case 'Newest':
        // 按最新排序
        sortColumn  = "createAt";
        orderBy = "1";
        break;
    }
    
    // 重新加载数据
    pageNo = 1;
    JOYProductList.clear();
    mainHomeBloc.add(GetJOYSearchCategoryProductEvent(
        context, chooseCategoryName, pageNo, pageSize,sortColumn: sortColumn,orderBy: orderBy));
  }
  

  Widget _buildProductCard(Map<String, dynamic> product) {
    return JoyProductCardWidget(
      onTap: () {
        // TODO: 跳转到商品详情页
        print('商品点击: ${product['title']}');
      },
      onFavorite: () {
        // TODO: 实现收藏功能
        print('收藏: ${product['title']}');
      },
    );
  }
}